<?
if (!defined('SMF'))
	die('Hacking attempt...');
	
function xenobetoship($xenobeinfo,$ship_id)
{
	global $smcFunc, $dbtables;
	global $attackerbeams, $attackerfighters, $attackershields;
	global $attackertorps, $attackerarmor, $attackertorpdamage;
	global $rating_combat_factor, $upgrade_cost, $upgrade_factor;
	global $start_energy, $sector_max, $level_factor, $torp_dmg_rate;

	/*
	$lock = $smcFunc['db_query']('', '
		LOCK TABLES
		{raw:db_ships} WRITE,
		{raw:db_universe} WRITE,
		{raw:db_bounty} WRITE,
		{raw:db_zones} READ,
		{raw:db_planets} READ,
		{raw:db_news} WRITE,
		{raw:db_logs} WRITE',
		array(
			'db_ships' => $dbtables['ships'],
			'db_universe' => $dbtables['universe'],
			'db_bounty' => $dbtables['bounty'],
			'db_zones' => $dbtables['zones'],
			'db_planets' => $dbtables['planets'],
			'db_news' => $dbtables['news'],
			'db_logs' => $dbtables['logs'],
		)
	);
	*/
	
	// Lookup target details
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_ships}
		WHERE ship_id = {int:ship_id}
		AND xenobe = "N"
		LIMIT 1',
		array(
			'db_ships' => $dbtables['ships'],
			'ship_id' => $ship_id,
		)
	);
	$targetinfo = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);

	// Verify sector allows attack
	$result = $smcFunc['db_query']('', '
		SELECT sector_id,zone_id
		FROM {raw:db_universe}
		WHERE sector_id = {int:sector}',
		array(
			'db_universe' => $dbtables['universe'],
			'sector' => $targetinfo['sector'],
		)
	);
	$sectrow = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
	
	$result = $smcFunc['db_query']('', '
		SELECT zone_id,allow_attack
		FROM {raw:db_zones}
		WHERE zone_id = {int:zone_id}',
		array(
			'db_zones' => $dbtables['zones'],
			'zone_id' => $sectrow['zone_id'],
		)
	);
	$zonerow = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);

	if ($zonerow['allow_attack'] == 'N')
	{
		playerlog($xenobeinfo['ship_id'], LOG_RAW, "Attack failed, you are in a sector that prohibits attacks."); 
		return false;
	}

	// Check for target EWD
	if ($targetinfo['dev_emerwarp'] > 0)
	{
		playerlog($targetinfo['ship_id'], LOG_ATTACK_EWD, "Xenobe $xenobeinfo[character_name]");
		$dest_sector = rand(0,$sector_max - 1);
		$smcFunc['db_query']('', '
			UPDATE {raw:db_ships}
			SET sector = {int:dest_sector},
				dev_emerwarp = dev_emerwarp - 1
			WHERE ship_id = {int:ship_id}',
			array(
				'db_ships' => $dbtables['ships'],
				'ship_id' => $targetinfo['ship_id'],
				'dest_sector' => $dest_sector,
			)
		);
		return false;
	}

	// Setup ATTACKER variables
	$attackerbeams = NUM_BEAMS($xenobeinfo['beams']);
	if ($attackerbeams > $xenobeinfo['ship_energy'])
		$attackerbeams = $xenobeinfo['ship_energy'];
	$xenobeinfo['ship_energy'] = $xenobeinfo['ship_energy'] - $attackerbeams;
	$attackershields = NUM_SHIELDS($xenobeinfo['shields']);
	if ($attackershields > $xenobeinfo['ship_energy'])
		$attackershields = $xenobeinfo['ship_energy'];
	$xenobeinfo['ship_energy'] = $xenobeinfo['ship_energy'] - $attackershields;
	$attackertorps = round(mypw($level_factor, $xenobeinfo['torp_launchers'])) * 2;
	if ($attackertorps > $xenobeinfo['torps'])
		$attackertorps = $xenobeinfo['torps'];
	$xenobeinfo['torps'] = $xenobeinfo['torps'] - $attackertorps;
	$attackertorpdamage = $torp_dmg_rate * $attackertorps;
	$attackerarmor = $xenobeinfo['armor_pts'];
	$attackerfighters = $xenobeinfo['ship_fighters'];
	$playerdestroyed = 0;

	// Setup TARGET variables
	$targetbeams = NUM_BEAMS($targetinfo['beams']);
	if ($targetbeams>$targetinfo['ship_energy'])
		$targetbeams = $targetinfo['ship_energy'];
	$targetinfo['ship_energy'] = $targetinfo['ship_energy'] - $targetbeams;
	$targetshields = NUM_SHIELDS($targetinfo['shields']);
	if ($targetshields > $targetinfo['ship_energy'])
		$targetshields = $targetinfo['ship_energy'];
	$targetinfo['ship_energy'] = $targetinfo['ship_energy'] - $targetshields;
	$targettorpnum = round(mypw($level_factor,$targetinfo['torp_launchers'])) * 2;
	if ($targettorpnum > $targetinfo['torps'])
		$targettorpnum = $targetinfo['torps'];
	$targetinfo['torps'] = $targetinfo['torps'] - $targettorpnum;
	$targettorpdmg = $torp_dmg_rate * $targettorpnum;
	$targetarmor = $targetinfo['armor_pts'];
	$targetfighters = $targetinfo['ship_fighters'];
	$targetdestroyed = 0;

	// Begin combat procedures
	
	// Attacker has beams - target has fighters - beams vs fighters
	if ($attackerbeams > 0 && $targetfighters > 0)
	{
		// Attacker beams greater than half of target fighters
		if ($attackerbeams > round($targetfighters / 2))
		{
			// Target loses half all fighters
			// Attacker loses beams equal to half of target fighters
			$lost = $targetfighters - (round($targetfighters / 2));
			$targetfighters = $targetfighters - $lost;
			$attackerbeams = $attackerbeams - $lost;
		}
		// Attacker beams less than half of target fighters
		else
		{
			// Target loses fighters equal to attacker beams
			// Attacker loses all beams
			$targetfighters = $targetfighters - $attackerbeams;
			$attackerbeams = 0;
		}   
	}
	
	// Target has beams - Attacker has fighters - beams vs fighters
	if ($attackerfighters > 0 && $targetbeams > 0)
	{
		// Target beams greater than half of attacker fighters
		if ($targetbeams > round($attackerfighters / 2))
		{
			// Attacker loses half all fighters
			// Target loses beams equal to half of target fighters
			$lost = $attackerfighters - (round($attackerfighters / 2));
			$attackerfighters = $attackerfighters - $lost;
			$targetbeams = $targetbeams - $lost;
		}
		// Target beams less than half of attacker fighters
		else
		{
			// Attacker loses fighters equal to target beams
			// Attacker loses all beams
			$attackerfighters = $attackerfighters - $targetbeams;
			$targetbeams = 0;
		}   
	}

	// Attacker has beams left - continue combat - beams vs shields
	if ($attackerbeams > 0)
	{
		// Attacker beams greater than target shields
		if ($attackerbeams > $targetshields)
		{
			// Attacker loses beams equal to target shields
			// Target loses all shields
			$attackerbeams = $attackerbeams - $targetshields;            
			$targetshields = 0;                                        
		}
		// Attacker beams less than target shields
		else
		{
			// Target loses shields equal to attacker beams
			// Attacker loses all beams
			$targetshields = $targetshields - $attackerbeams;
			$attackerbeams = 0;
		}
	}
  
	// Target has beams left - continue combat - beams vs shields
	if ($targetbeams > 0)
	{
		// Target beams greater than attacker shields
		if ($targetbeams > $attackershields)
		{
			// Target loses beams equal to attacker shields
			// Attacker loses all shields
			$targetbeams = $targetbeams - $attackershields;            
			$attackershields = 0;                                        
		}
		// Target beams less than attacker shields
		else
		{
			// Attacker loses shields equal to target beams
			// Target loses all beams
			$attackershields = $attackershields - $targetbeams;
			$targetbeams = 0;
		}
	}

	// Attacker has beams left - continue combat - beams vs armor
	if ($attackerbeams > 0)
	{
		// Attacker beams greater than target armor
		if ($attackerbeams > $targetarmor)
		{
			// Attacker loses beams equal to target armor
			// Target loses all armor
			$attackerbeams = $attackerbeams - $targetarmor;            
			$targetarmor = 0;                                        
		}
		// Attacker beams less than target armor
		else
		{
			// Target loses armor equal to attacker beams
			// Attacker loses all beams
			$targetarmor = $targetarmor - $attackerbeams;
			$attackerbeams = 0;
		}
	}
  
	// Target has beams left - continue combat - beams vs armor
	if ($targetbeams > 0)
	{
		// Target beams greater than attacker armor
		if ($targetbeams > $attackerarmor)
		{
			// Target loses beams equal to attacker armor
			// Attacker loses all armor
			$targetbeams = $targetbeams - $attackerarmor;            
			$attackerarmor = 0;                                        
		}
		// Target beams less than attacker armor
		else
		{
			// Attacker loses armor equal to target beams
			// Target loses all beams
			$attackerarmor = $attackerarmor - $targetbeams;
			$targetbeams = 0;
		}
	}

	// Attacker has torps - target has fighters - torps vs fighters
	if ($targetfighters > 0 && $attackertorpdamage > 0)
	{
		// Attacker torps greater than half of target fighters
		if ($attackertorpdamage > round($targetfighters / 2))
		{
			// Target loses half all fighters
			// Attacker loses half torps equal to half of target fighters
			$lost = $targetfighters - (round($targetfighters / 2));
			$targetfighters = $targetfighters - $lost;
			$attackertorpdamage = $attackertorpdamage - $lost;
		}
		// Attacker torps less than half of target fighters
		else
		{
			// Target loses fighters equal to attacker torps
			// Attacker loses all torps
			$targetfighters = $targetfighters - $attackertorpdamage;
			$attackertorpdamage = 0;
		}   
	}
	
	// Target has torps - Attacker has fighters - torps vs fighters
	if ($attackerfighters > 0 && $targettorpdmg > 0)
	{
		// Target torps greater than half of attacker fighters
		if ($targettorpdmg > round($attackerfighters / 2))
		{
			// Attacker loses half all fighters
			// Target loses torps equal to half of target fighters
			$lost = $attackerfighters - (round($attackerfighters / 2));
			$attackerfighters = $attackerfighters - $lost;
			$targettorpdmg = $targettorpdmg - $lost;
		}
		// Target torps less than half of attacker fighters
		else
		{
			// Attacker loses fighters equal to target torps
			// Attacker loses all torps
			$attackerfighters = $attackerfighters - $targettorpdmg;
			$targettorpdmg = 0;
		}   
	}
  
	// Attacker has beams torps - continue combat - torps vs armor
	if ($attackertorpdamage > 0)
	{
		// Attacker torps greater than target armor
		if ($attackertorpdamage > $targetarmor)
		{
			// Attacker loses torps equal to target armor
			// Target loses all armor - destroyed
			$attackertorpdamage = $attackertorpdamage - $targetarmor;            
			$targetarmor = 0;                                        
		}
		// Attacker torps less than target armor
		else
		{
			// Target loses armor equal to attacker torps
			// Attacker loses all torps
			$targetarmor = $targetarmor - $attackertorpdamage;
			$attackertorpdamage = 0;
		}
	}
	
	// Target has torps left - continue combat - torps vs armor
	if ($targettorpdmg > 0)
	{
		// Target torps greater than attacker armor
		if ($targettorpdmg > $attackerarmor)
		{
			// Target loses torps equal to attacker armor
			// Attacker loses all armor - destroyed
			$targettorpdmg = $targettorpdmg - $attackerarmor;            
			$attackerarmor = 0;                                        
		}
		// Target torps less than attacker armor
		else
		{
			// Attacker loses armor equal to target torps
			// Target loses all torps
			$attackerarmor = $attackerarmor - $targettorpdmg;
			$targettorpdmg = 0;
		}
	}
  
	// Attacker has fighters - target has fighters - fighters vs fighters
	if ($attackerfighters > 0 && $targetfighters > 0)
	{
		// Attacker fighters greater than target fighters
		if ($attackerfighters > $targetfighters)
			// Target will lose all fighters
			$temptargfighters = 0;
		// Attacker fighters less than target fighters
		else
			// Target will lose fighters equal to attacker fighters
			$temptargfighters = $targetfighters - $attackerfighters;
		
		// Target fighters greater than attacker fighters
		if ($targetfighters > $attackerfighters)
			// Attacker will lose all fighters
			$tempplayfighters=0;
		// Target fighters less than attacker fighters
		else
			// Attacker will lose fighters equal to target fighters
			$tempplayfighters=$attackerfighters-$targetfighters;
			
		$attackerfighters = $tempplayfighters;
		$targetfighters = $temptargfighters;
	}
	
	// Attacker has fighters - continue combat - fighters vs armor
	if ($attackerfighters > 0)
	{
		// Attacker fighters greater than target armor
		if ($attackerfighters > $targetarmor)
			// Target loses all armor - target destroyed
			$targetarmor = 0;
		// Attacker fighters less than target armor
		else
			// Target looses armor equal to attacker fighters
			$targetarmor = $targetarmor - $attackerfighters;
	}
  
	// Target has fighters - continue combat - fighters vs armor
	if ($targetfighters > 0)
	{
		// Target fighters greater than attacker armor
		if ($targetfighters > $attackerarmor)
			// Attacker loses all armor - attacker destroyed
			$attackerarmor = 0;
		// Target fighters less than attacker armor
		else
			// Attacker looses armor equal to target fighters
			$attackerarmor = $attackerarmor - $targetfighters;
	}

	// Check for and fix negative value vars
	$attackerfighters = ($attackerfighters < 0) ? 0 : $attackerfighters;
	$attackershields = ($attackershields < 0) ? 0 : $attackershields;
	$attackerbeams = ($attackerbeams < 0) ? 0 : $attackerbeams;
	$attackerarmor = ($attackerarmor < 0) ? 0 : $attackerarmor;
	
	$targetfighters = ($targetfighters < 0) ? 0 : $targetfighters;
	$targettorpnum = ($targettorpnum < 0) ? 0 : $targettorpnum;
	$targetshields = ($targetshields < 0) ? 0 : $targetshields;
	$targetbeams = ($targetbeams < 0) ? 0 : $targetbeams;
	$targetarmor = ($targetarmor < 0) ? 0 : $targetarmor;

	// Check if target ship was destroyed
	if ($targetarmor <= 0)
	{
		// Check for target escape pod
		if ($targetinfo['dev_escapepod'] == 'Y')
		{
			$rating = round($targetinfo['rating'] / 2);
			
			$smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET hull = 0,
					engines = 0,
					power = 0,
					sensors = 0,
					computer = 0,
					beams = 0,
					torp_launchers = 0,
					torps = 0,
					armor = 0,
					armor_pts = 100,
					cloak = 0,
					shields = 0,
					sector = 0,
					ship_organics = 0,
					ship_ore = 0,
					ship_goods = 0,
					ship_energy = {int:start_energy},
					ship_colonists = 0,
					ship_fighters = 100,
					dev_warpedit = 0,
					dev_genesis = 0,
					dev_beacon = 0,
					dev_emerwarp = 0,
					dev_escapepod = "N",
					dev_fuelscoop = "N",
					dev_minedeflector = 0,
					on_planet = "N",
					rating = {int:rating},
					cleared_defences = NULL,
					dev_lssd = "N"
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $targetinfo['ship_id'],
					'start_energy' => $start_energy,
					'rating' => $rating
				)
			);
			
			playerlog($targetinfo['ship_id'], LOG_ATTACK_LOSE, "Xenobe $xenobeinfo[character_name]|Y"); 
		}
		else
		{
			playerlog($targetinfo['ship_id'], LOG_ATTACK_LOSE, "Xenobe $xenobeinfo[character_name]|N"); 
			db_kill_player($targetinfo['ship_id']);
		}   
		
		// Check if attacker still alive to salvage traget
		if ($attackerarmor > 0)
		{
			$xenobeisdead = false;
			
			$rating_change = round($targetinfo['rating'] * $rating_combat_factor);
			$free_ore = round($targetinfo['ship_ore'] / 2);
			$free_organics = round($targetinfo['ship_organics'] / 2);
			$free_goods = round($targetinfo['ship_goods'] / 2);
			$free_holds = NUM_HOLDS($xenobeinfo['hull']) - $xenobeinfo['ship_ore'] - $xenobeinfo['ship_organics'] - $xenobeinfo['ship_goods'] - $xenobeinfo['ship_colonists'];
			
			if ($free_holds > $free_goods) 
			{
				$salv_goods = $free_goods;
				$free_holds = $free_holds - $free_goods;
			}
			elseif ($free_holds > 0)
			{
				$salv_goods = $free_holds;
				$free_holds = 0;
			}
			else
				$salv_goods = 0;
			
			if ($free_holds > $free_ore)
			{
				$salv_ore = $free_ore;
				$free_holds = $free_holds - $free_ore;
			}
			elseif ($free_holds > 0)
			{
				$salv_ore = $free_holds;
				$free_holds = 0;
			}
			else
				$salv_ore = 0;
			
			if ($free_holds > $free_organics)
			{
				$salv_organics = $free_organics;
				$free_holds = $free_holds - $free_organics;
			}
			elseif ($free_holds > 0)
			{
				$salv_organics = $free_holds;
				$free_holds = 0;
			}
			else
				$salv_organics = 0;
			
			$ship_value = $upgrade_cost * (round(mypw($upgrade_factor, $targetinfo['hull'])) + round(mypw($upgrade_factor, $targetinfo['engines'])) + round(mypw($upgrade_factor, $targetinfo['power'])) + round(mypw($upgrade_factor, $targetinfo['computer'])) + round(mypw($upgrade_factor, $targetinfo['sensors'])) + round(mypw($upgrade_factor, $targetinfo['beams'])) + round(mypw($upgrade_factor, $targetinfo['torp_launchers'])) + round(mypw($upgrade_factor, $targetinfo['shields'])) + round(mypw($upgrade_factor, $targetinfo['armor'])) + round(mypw($upgrade_factor, $targetinfo['cloak'])));
			$ship_salvage_rate = rand(10,20);
			$ship_salvage = round($ship_value * $ship_salvage_rate / 100);
			
			playerlog($xenobeinfo['ship_id'], LOG_RAW, "Attack successful, $targetinfo[character_name] was defeated and salvaged for $ship_salvage credits."); 
			
			$smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET ship_ore = ship_ore + {int:salv_ore}, 
					ship_organics = ship_organics + {int:salv_organics}, 
					ship_goods = ship_goods + {int:salv_goods}, 
					credits = credits + {float:ship_salvage}
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $xenobeinfo['ship_id'],
					'salv_ore' => $salv_ore,
					'salv_organics' => $salv_organics,
					'salv_goods' => $salv_goods,
					'ship_salvage' => $ship_salvage
				)
			);
			
			$armor_lost = $xenobeinfo['armor_pts'] - $attackerarmor;
			$fighters_lost = $xenobeinfo['ship_fighters'] - $attackerfighters;
			$energy = $xenobeinfo['ship_energy'];
			
			$smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET ship_energy = {int:energy},
					ship_fighters = ship_fighters - {int:fighters_lost},
					armor_pts = armor_pts - {int:armor_lost}, 
					torps = torps - {int:playertorpnum}, 
					rating = rating - {int:rating_change} 
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $xenobeinfo['ship_id'],
					'energy' => $energy,
					'fighters_lost' => $fighters_lost,
					'armor_lost' => $armor_lost,
					'playertorpnum' => $attackertorps,
					'rating_change' => $rating_change
				)
			);
		}
	}

	// Check if target and attacker live
	if ($targetarmor > 0 && $attackerarmor > 0)
	{
		$xenobeisdead = false;
		
		$rating_change = round($targetinfo['rating'] * .1);
		$armor_lost = $xenobeinfo['armor_pts'] - $attackerarmor;
		$fighters_lost = $xenobeinfo['ship_fighters'] - $attackerfighters;
		$energy = $xenobeinfo['ship_energy'];
		
		$target_rating_change = round($targetinfo['rating'] / 2);
		$target_armor_lost = $targetinfo['armor_pts'] - $targetarmor;
		$target_fighters_lost = $targetinfo['ship_fighters'] - $targetfighters;
		$target_energy = $targetinfo['ship_energy'];
		
		playerlog($xenobeinfo['ship_id'], LOG_RAW, "Attack failed, $targetinfo[character_name] survived."); 
		playerlog($targetinfo['ship_id'], LOG_ATTACKED_WIN, "Xenobe $xenobeinfo[character_name]|$target_armor_lost|$target_fighters_lost");
		
		$smcFunc['db_query']('', '
			UPDATE {raw:db_ships}
			SET ship_energy = {int:energy},
				ship_fighters = ship_fighters - {int:fighters_lost},
				armor_pts = armor_pts - {int:armor_lost}, 
				torps = torps - {int:attackertorps},
				rating = rating - {int:rating_change}
			WHERE ship_id = {int:ship_id}',
			array(
				'db_ships' => $dbtables['ships'],
				'ship_id' => $xenobeinfo['ship_id'],
				'energy' => $energy,
				'fighters_lost' => $fighters_lost,
				'armor_lost' => $armor_lost,
				'attackertorps' => $attackertorps,
				'rating' => $rating_change
			)
		);
		
		$smcFunc['db_query']('', '
			UPDATE {raw:db_ships}
			SET ship_energy = {int:energy},
				ship_fighters = ship_fighters - {int:fighters_lost},
				armor_pts = armor_pts - {int:armor_lost}, 
				torps = torps - {int:attackertorps},
				rating = rating - {int:rating_change}
			WHERE ship_id = {int:ship_id}',
			array(
				'db_ships' => $dbtables['ships'],
				'ship_id' => $targetinfo['ship_id'],
				'energy' => $target_energy,
				'fighters_lost' => $target_fighters_lost,
				'armor_lost' => $target_armor_lost,
				'attackertorps' => $targettorpnum,
				'rating' => $target_rating_change
			)
		);
	}


	// Check if attacker ship destroyed
	if ($attackerarmor <= 0)
	{
		playerlog($xenobeinfo['ship_id'], LOG_RAW, "$targetinfo[character_name] destroyed your ship!"); 
		db_kill_player($xenobeinfo['ship_id']);
		
		$xenobeisdead = true;
		
		$target_rating_change = round($targetinfo['rating'] / 2);
		$target_armor_lost = $targetinfo['armor_pts'] - $targetarmor;
		$target_fighters_lost = $targetinfo['ship_fighters'] - $targetfighters;
		$target_energy = $targetinfo['ship_energy'];
		
		// Check if target still alive to salvage attacker
		if ($targetarmor > 0)
		{
			$rating_change = round($xenobeinfo['rating'] * $rating_combat_factor);
			$free_ore = round($xenobeinfo['ship_ore'] / 2);
			$free_organics = round($xenobeinfo['ship_organics'] / 2);
			$free_goods = round($xenobeinfo['ship_goods'] / 2);
			$free_holds = NUM_HOLDS($targetinfo['hull']) - $targetinfo['ship_ore'] - $targetinfo['ship_organics'] - $targetinfo['ship_goods'] - $targetinfo['ship_colonists'];
			
			if ($free_holds > $free_goods) 
			{
				$salv_goods = $free_goods;
				$free_holds = $free_holds - $free_goods;
			}
			elseif ($free_holds > 0)
			{
				$salv_goods = $free_holds;
				$free_holds = 0;
			}
			else
				$salv_goods = 0;
			
			if ($free_holds > $free_ore)
			{
				$salv_ore = $free_ore;
				$free_holds =$free_holds - $free_ore;
			}
			elseif ($free_holds > 0)
			{
				$salv_ore = $free_holds;
				$free_holds = 0;
			}
			else
				$salv_ore = 0;
			
			if ($free_holds > $free_organics)
			{
				$salv_organics = $free_organics;
				$free_holds = $free_holds - $free_organics;
			}
			elseif ($free_holds > 0)
			{
				$salv_organics = $free_holds;
				$free_holds = 0;
			}
			else
				$salv_organics = 0;
			
			$ship_value = $upgrade_cost * (round(mypw($upgrade_factor, $xenobeinfo['hull'])) + round(mypw($upgrade_factor, $xenobeinfo['engines'])) + round(mypw($upgrade_factor, $xenobeinfo['power'])) + round(mypw($upgrade_factor, $xenobeinfo['computer'])) + round(mypw($upgrade_factor, $xenobeinfo['sensors'])) + round(mypw($upgrade_factor, $xenobeinfo['beams'])) + round(mypw($upgrade_factor, $xenobeinfo['torp_launchers'])) + round(mypw($upgrade_factor, $xenobeinfo['shields'])) + round(mypw($upgrade_factor, $xenobeinfo['armor'])) + round(mypw($upgrade_factor, $xenobeinfo['cloak'])));
			$ship_salvage_rate = rand(10,20);
			$ship_salvage = $ship_value * $ship_salvage_rate / 100;
			
			playerlog($targetinfo['ship_id'], LOG_ATTACKED_WIN, "Xenobe $xenobeinfo[character_name]|$target_armor_lost|$target_fighters_lost");
			playerlog($targetinfo['ship_id'], LOG_RAW, "You destroyed the Xenobe ship and salvaged $salv_ore units of ore, $salv_organics units of organics, $salv_goods units of goods, and salvaged $ship_salvage_rate% of the ship for $ship_salvage credits.");
			
			$smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET ship_ore = ship_ore + {int:salv_ore}, 
					ship_organics = ship_organics + {int:salv_organics}, 
					ship_goods = ship_goods + {int:salv_goods}, 
					credits = credits + {float:ship_salvage}
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $targetinfo['ship_id'],
					'salv_ore' => $salv_ore,
					'salv_organics' => $salv_organics,
					'salv_goods' => $salv_goods,
					'ship_salvage' => $ship_salvage
				)
			);
			
			$armor_lost = $targetinfo['armor_pts'] - $targetarmor;
			$fighters_lost = $targetinfo['ship_fighters'] - $targetfighters;
			$energy=$targetinfo['ship_energy'];
			
			$smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET ship_energy = {int:energy},
					ship_fighters = ship_fighters - {int:fighters_lost},
					armor_pts = armor_pts - {int:armor_lost}, 
					torps = torps - {int:playertorpnum}, 
					rating = rating - {int:rating_change} 
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $targetinfo['ship_id'],
					'energy' => $energy,
					'fighters_lost' => $fighters_lost,
					'armor_lost' => $armor_lost,
					'playertorpnum' => $attackertorps,
					'rating_change' => $rating_change
				)
			);
		}
	}

// $unlock = $smcFunc['db_query']('', 'UNLOCK TABLES');

	return $xenobeisdead;
}

function xenobetosecdef($xenobeinfo,$targetlink)
{
	global $smcFunc, $txt, $dbtables;
	global $level_factor, $torp_dmg_rate;

	if ($targetlink > 0)
	{
		$result = $smcFunc['db_query']('', '
			SELECT *
			FROM {raw:db_sector_defence}
			WHERE sector_id = {int:targetlink}
			AND defence_type = "F"',
			array(
				'db_sector_defence' => $dbtables['sector_defence'],
				'targetlink' => $targetlink,
			)
		);
		$i = 0;
		$total_sector_fighters = 0;
		
		while ($defences[$i] = $smcFunc['db_fetch_assoc']($result))
		{
			$total_sector_fighters += $defences[$i]['quantity'];
			$i++;
		}
		$smcFunc['db_free_result']($result);
		
		$result = $smcFunc['db_query']('', '
			SELECT *
			FROM {raw:db_sector_defence}
			WHERE sector_id = {int:targetlink}
			AND defence_type = "M"',
			array(
				'db_sector_defence' => $dbtables['sector_defence'],
				'targetlink' => $targetlink,
			)
		);
		$i = 0;
		$total_sector_mines = 0;
		
		while ($defences[$i] = $smcFunc['db_fetch_assoc']($result))
		{
			$total_sector_mines += $defences[$i]['quantity'];
			$i++;
		}
		$smcFunc['db_free_result']($result);

		// If sector has defences, attack them.
		if ($total_sector_fighters > 0)
		{
			playerlog($xenobeinfo['ship_id'], LOG_RAW, "ATTACKING SECTOR DEFENCES $total_sector_fighters fighters and $total_sector_mines mines."); 
			
			$targetfighters = $total_sector_fighters;
			
			$playerbeams = NUM_BEAMS($xenobeinfo['beams']);
			if ($playerbeams > $xenobeinfo['ship_energy'])
				$playerbeams = $xenobeinfo['ship_energy'];
	  
			$xenobeinfo['ship_energy'] = $xenobeinfo['ship_energy'] - $playerbeams;
      
			$playershields = NUM_SHIELDS($xenobeinfo['shields']);
			if ($playershields > $xenobeinfo['ship_energy'])
				$playershields = $xenobeinfo['ship_energy'];
	  
			$playertorpnum = round(mypw($level_factor,$xenobeinfo['torp_launchers'])) * 2;
			if ($playertorpnum > $xenobeinfo['torps'])
				$playertorpnum = $xenobeinfo['torps'];
				
			$playertorpdmg = $torp_dmg_rate * $playertorpnum;
			$playerarmor = $xenobeinfo['armor_pts'];
			$playerfighters = $xenobeinfo['ship_fighters'];

			// Beams vs fighters
			if ($targetfighters > 0 && $playerbeams > 0)
			{
				if ($playerbeams > round($targetfighters / 2))
				{
					$temp = round($targetfighters / 2);
					$targetfighters = $temp;
					$playerbeams = $playerbeams - $temp;
				}
				else
				{
					$targetfighters = $targetfighters - $playerbeams;
					$playerbeams = 0;
				}   
			}
	  
			// Torps vs fighters
			if ($targetfighters > 0 && $playertorpdmg > 0)
			{
				if ($playertorpdmg > round($targetfighters / 2))
				{
					$temp = round($targetfighters / 2);
					$targetfighters = $temp;
					$playertorpdmg = $playertorpdmg - $temp;
				}
				else
				{
					$targetfighters = $targetfighters - $playertorpdmg;
					$playertorpdmg = 0;
				}
			}
	  
			// Fighters vs fighters
			if ($playerfighters > 0 && $targetfighters > 0)
			{
				if ($playerfighters > $targetfighters)
					$temptargfighters = 0;
				else
					$temptargfighters = $targetfighters - $playerfighters;
					
				if ($targetfighters > $playerfighters)
					$tempplayfighters = 0;
				else
					$tempplayfighters = $playerfighters - $targetfighters;
					
				$playerfighters = $tempplayfighters;
				$targetfighters = $temptargfighters;
			}

			// Armour vs fighters
			if ($targetfighters > 0)
			{
				if ($targetfighters > $playerarmor)
					$playerarmor = 0;
				else
					$playerarmor = $playerarmor - $targetfighters;
			}
	  
			// Get rid of the sector fighters that died
			$fighterslost = $total_sector_fighters - $targetfighters;
			destroy_fighters($targetlink,$fighterslost);

			// Let defence owner know what happened 
			$txt['bnt_sf_sendlog'] = str_replace("[player]", 'Xenobe ' . $xenobeinfo['character_name'], $txt['bnt_sf_sendlog']);
			$txt['bnt_sf_sendlog'] = str_replace("[lost]", $fighterslost, $txt['bnt_sf_sendlog']);
			$txt['bnt_sf_sendlog'] = str_replace("[sector]", $targetlink, $txt['bnt_sf_sendlog']);
			message_defence_owner($targetlink,$txt['bnt_sf_sendlog']);

			// Update xenobe
			$armor_lost = $xenobeinfo['armor_pts'] - $playerarmor;
			$fighters_lost = $xenobeinfo['ship_fighters'] - $playerfighters;
			$ship_energy = $xenobeinfo['ship_energy'];
			
			$smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET ship_energy = {int:ship_energy},
					ship_fighters = ship_fighters - {int:fighters_lost},
					armor_pts = armor_pts - {int:armor_lost},
					torps = torps - {int:playertorpnum}
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_energy' => $ship_energy,
					'fighters_lost' => $fighters_lost,
					'armor_lost' => $armor_lost,
					'playertorpnum' => $playertorpnum,
					'ship_id' => $xenobeinfo['ship_id']
				)
			);
			
			// Check to see if Xenobe is dead
			if ($playerarmor < 1)
			{
				$txt['bnt_sf_sendlog2'] = str_replace("[player]", 'Xenobe ' . $xenobeinfo['character_name'], $txt['bnt_sf_sendlog2']);
				$txt['bnt_sf_sendlog2'] = str_replace("[sector]", $targetlink, $txt['bnt_sf_sendlog2']);
				message_defence_owner($targetlink,$txt['bnt_sf_sendlog2']);
				cancel_bounty($xenobeinfo['ship_id']);
				db_kill_player($xenobeinfo['ship_id']);
				return true;
			}
		}
		
		// Survived fighters, check for mines
		if ($total_sector_mines > 0)
		{
			// Refresh xenobe information
			$result = $smcFunc['db_query']('', '
				SELECT *
				FROM {raw:db_ships}
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $xenobeinfo['ship_id'],
				)
			);
			$xenobeinfo = $smcFunc['db_fetch_assoc']($result);
			$smcFunc['db_free_result']($result);
			
			$playershields = NUM_SHIELDS($xenobeinfo['shields']);
			$playerarmor = $xenobeinfo['armor_pts'];
			
			$totalmines = $total_sector_mines;
			
			if ($totalmines > 1)
				$roll = rand(1,$totalmines);
			else
				$roll = 1;
				
			$totalmines = $totalmines - $roll;
			
			// Xenobe keep as many deflectors as fighters
			$playerminedeflect = $xenobeinfo['ship_fighters'];
		
			// Log mine encounter
			$txt['bnt_chm_hehitminesinsector'] = str_replace("[chm_playerinfo_character_name]", "Xenobe " . $xenobeinfo['character_name'], $txt['bnt_chm_hehitminesinsector']);
			$txt['bnt_chm_hehitminesinsector']= str_replace("[chm_roll]", $roll, $txt['bnt_chm_hehitminesinsector']);
			$txt['bnt_chm_hehitminesinsector'] = str_replace("[chm_sector]", $targetlink, $txt['bnt_chm_hehitminesinsector']);
			message_defence_owner($targetlink,$txt['bnt_chm_hehitminesinsector']);

			// Deflectors vs mines
			if ($playerminedeflect >= $roll) {
				// Took no mine damage due to virtual mine deflectors
			}
			else
			{
				$mines_left = $roll - $playerminedeflect;

				// Shields vs mines
				if ($playershields >= $mines_left)
					$smcFunc['db_query']('', '
						UPDATE {raw:db_ships}
						SET ship_energy = ship_energy - {int:mines_left}
						WHERE ship_id = {int:ship_id}',
						array(
							'db_ships' => $dbtables['ships'],
							'mines_left' => $mines_left,
							'ship_id' => $xenobeinfo['ship_id']
						)
					);
				else
				{
					$mines_left = $mines_left - $playershields;

					// Armour vs mines
					if ($playerarmor >= $mines_left)
						$smcFunc['db_query']('', '
							UPDATE {raw:db_ships}
							SET armor_pts = armor_pts - {int:mines_left},
								ship_energy = 0
							WHERE ship_id = {int:ship_id}',
							array(
								'db_ships' => $dbtables['ships'],
								'mines_left' => $mines_left,
								'ship_id' => $xenobeinfo['ship_id']
							)
						);
					else
					{
						// Armor 0 = death, log xenobe death
						$txt['bnt_chm_hewasdestroyedbyyourmines'] = str_replace("[chm_playerinfo_character_name]", 'Xenobe ' . $xenobeinfo['character_name'], $txt['bnt_chm_hewasdestroyedbyyourmines']);
						$txt['bnt_chm_hewasdestroyedbyyourmines'] = str_replace("[chm_sector]", $targetlink, $txt['bnt_chm_hewasdestroyedbyyourmines']);
						message_defence_owner($targetlink,$txt['bnt_chm_hewasdestroyedbyyourmines']);
						
						// Kill the xenobe
						cancel_bounty($xenobeinfo['ship_id']);
						db_kill_player($xenobeinfo['ship_id']);
						
						// Explode excess mines
						explode_mines($targetlink,$roll);
						return true;
					}
				}
			}
			
			// Get rid of excess mines
			explode_mines($targetlink,$roll);
		}
		else
			return false;
	}
}


function xenobemove($xenobeinfo,$targetlink)
{
	global $smcFunc, $dbtables;
	global $sector_max;

	// Obtain a target sector from the current sector's warp links
	if ($targetlink == $xenobeinfo['sector'])
		$targetlink = 0;

	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_links}
		WHERE link_start = {int:sector}',
		array(
			'db_links' => $dbtables['links'],
			'sector' => $xenobeinfo['sector'],
		)
	);	
	
	// Parse through the warp link results
	while ($row = $smcFunc['db_fetch_assoc']($result))
	{
		// Obtain sector & zone information
		$sector_result = $smcFunc['db_query']('', '
			SELECT sector_id, zone_id
			FROM {raw:db_universe}
			WHERE sector_id = {int:link_dest}',
			array(
				'db_universe' => $dbtables['universe'],
				'link_dest' => $row['link_dest'],
			)
		);
		$sectrow = $smcFunc['db_fetch_assoc']($sector_result);
		$smcFunc['db_free_result']($sector_result);
		
		$zone_result = $smcFunc['db_query']('', '
			SELECT zone_id, allow_attack
			FROM {raw:db_zones}
			WHERE zone_id = {int:zone_id}',
			array(
				'db_zones' => $dbtables['zones'],
				'zone_id' => $sectrow['zone_id'],
			)
		);
		$zonerow = $smcFunc['db_fetch_assoc']($zone_result);
		$smcFunc['db_free_result']($zone_result);
		
		// Check if destination link allows attacking
		if ($zonerow['allow_attack'] == 'Y')                        
		{
			// 33% chance of replacing dest link with this one
			$setlink = rand(0,2);                        
			if ($setlink == 0 || !$targetlink > 0)
				$targetlink = $row['link_dest'];
		}
	}

	// If an acceptable link was not found, realspace to random sector
	if (!$targetlink > 0)
	{
		// Generate a random sector number
		$wormto = rand(1,$sector_max - 1);
		$limitloop = 1;
		while (!$targetlink > 0 && $limitloop < 15)
		{
			// Obtain sector & zone information
			$sector_result = $smcFunc['db_query']('', '
				SELECT sector_id, zone_id
				FROM {raw:db_universe}
				WHERE sector_id = {int:wormto}',
				array(
					'db_universe' => $dbtables['universe'],
					'wormto' => $wormto,
				)
			);
			$sectrow = $smcFunc['db_fetch_assoc']($sector_result);
			$smcFunc['db_free_result']($sector_result);
			
			$zone_result = $smcFunc['db_query']('', '
				SELECT zone_id, allow_attack
				FROM {raw:db_zones}
				WHERE zone_id = {int:zone_id}',
				array(
					'db_zones' => $dbtables['zones'],
					'zone_id' => $sectrow['zone_id'],
				)
			);
			$zonerow = $smcFunc['db_fetch_assoc']($zone_result);
			$smcFunc['db_free_result']($zone_result);

			if ($zonerow['allow_attack']=="Y")
			{
				$targetlink = $wormto;
				playerlog($xenobeinfo['ship_id'], LOG_RAW, "Realspace move to a zone where attacks are allowed."); 
			}
			$wormto++;
			$wormto++;
			$limitloop++;
		}
	} 

	// Check for sector defences
	if ($targetlink > 0)
	{
		$result = $smcFunc['db_query']('', '
			SELECT *
			FROM {raw:db_sector_defence}
			WHERE sector_id = {int:targetlink}
			AND defence_type = "F"',
			array(
				'db_sector_defence' => $dbtables['sector_defence'],
				'targetlink' => $targetlink,
			)
		);
		
		$i = 0;
		$total_sector_fighters = 0;
		
		while ($defences[$i] = $smcFunc['db_fetch_assoc']($result))
		{
			$total_sector_fighters += $defences[$i]['quantity'];
			$i++;
		}
		$smcFunc['db_free_result']($result);
		
		$result = $smcFunc['db_query']('', '
			SELECT *
			FROM {raw:db_sector_defence}
			WHERE sector_id = {int:targetlink}
			AND defence_type = "M"',
			array(
				'db_sector_defence' => $dbtables['sector_defence'],
				'targetlink' => $targetlink,
			)
		);
		
		$i = 0;
		$total_sector_mines = 0;
		
		while ($defences[$i] = $smcFunc['db_fetch_assoc']($result))
		{
			$total_sector_mines += $defences[$i]['quantity'];
			$i++;
		}
		$smcFunc['db_free_result']($result);
		
		// Check if destination has sector defences
		if ($total_sector_fighters > 0 || $total_sector_mines > 0)
		{
			// Check xenobe aggression level to determine if xenobe attacks defences
			if ($xenobeinfo['aggression'] == 2 || $xenobeinfo['aggression'] == 1)
			{
				$xenobeisdead = xenobetosecdef($xenobeinfo,$targetlink);
				return $xenobeisdead;
			}
			else
			{
				playerlog($xenobeinfo['ship_id'], LOG_RAW, "Move failed, the sector is defended by $total_sector_fighters fighters and $total_sector_mines mines."); 
				return;
			}
		}
	}

	// Initiate move to target sector
	if ($targetlink > 0)
	{
		$result = $smcFunc['db_query']('', '
			UPDATE {raw:db_ships}
			SET last_login = NOW(),
				turns_used = turns_used + 1,
				sector = {int:targetlink}
			WHERE ship_id = {int:ship_id}',
			array(
				'db_ships' => $dbtables['ships'],
				'targetlink' => $targetlink,
				'ship_id' => $xenobeinfo['ship_id']
			)
		);

		if (!$result)
		{
			playerlog($xenobeinfo['ship_id'], LOG_RAW, "Move to $targetlink failed."); 
		}
		else
		{
			// playerlog($xenobeinfo[ship_id], LOG_RAW, "Moved to $targetlink without incident."); 
		}
	}
	else
	{
		playerlog($xenobeinfo['ship_id'], LOG_RAW, "Move failed due to lack of target link.");
		$targetlink = $xenobeinfo['sector'];
	}
}

function xenoberegen($xenobeinfo)
{
	global $smcFunc, $dbtables;
	global $xen_unemployment;
	
	$gena = '';
	$gene = '';
	$genf = '';
	$gent = '';
	
	// Xenobe Unempoyment Check
	$xenobeinfo['credits'] = $xenobeinfo['credits'] + $xen_unemployment;
  
	/*
		Regenerate ENERGY:
		Stop regen when within 50 of max 
		Regen half of remaining energy
	*/
	$maxenergy = NUM_ENERGY($xenobeinfo['power']);
	if ($xenobeinfo['ship_energy'] <= ($maxenergy - 50))
	{
		$xenobeinfo['ship_energy'] = $xenobeinfo['ship_energy'] + round(($maxenergy - $xenobeinfo['ship_energy']) / 2);
		$gene = 'regenerated energy to ' . $xenobeinfo['ship_energy'] . ' units,';
	}
	
	/*
		Regenerate ARMOR:
		Stop regen when within 50 of max 
		Regen half of remaining armor
	*/
	$maxarmor = NUM_ARMOUR($xenobeinfo['armor']);
	if ($xenobeinfo['armor_pts'] <= ($maxarmor - 50))
	{
		$xenobeinfo['armor_pts'] = $xenobeinfo['armor_pts'] + round(($maxarmor - $xenobeinfo['armor_pts']) / 2);
		$gena = 'regenerated armour to ' . $xenobeinfo['armor_pts'] . ' points,';
	}
		
	/*
		Buy Fighters / Torps
		Xenobe's pay 6 per fighter
		Xenobe's pay 3 per torpedo
	*/
	$available_fighters = NUM_FIGHTERS($xenobeinfo['computer']) - $xenobeinfo['ship_fighters'];
	if (($xenobeinfo['credits'] > 5) && ($available_fighters > 0))
	{
		if (round($xenobeinfo['credits'] / 6) > $available_fighters)
		{
			$purchase = ($available_fighters * 6);
			$xenobeinfo['credits'] = $xenobeinfo['credits'] - $purchase;
			$xenobeinfo['ship_fighters'] = $xenobeinfo['ship_fighters'] + $available_fighters;
			$genf = 'purchased ' . $available_fighters . ' fighters for ' . $purchase . ' credits,';
		}
		if (round($xenobeinfo['credits'] / 6) <= $available_fighters)
		{
			$purchase = (round($xenobeinfo['credits'] / 6));
			$xenobeinfo['ship_fighters'] = $xenobeinfo['ship_fighters'] + $purchase;
			$genf = 'purchased ' . $purchase . ' fighters for ' . $xenobeinfo['credits'] . ' credits,';
			$xenobeinfo['credits'] = 0;
		}
	}
	
	$available_torpedoes = NUM_TORPEDOES($xenobeinfo['torp_launchers']) - $xenobeinfo['torps'];
	if (($xenobeinfo['credits'] > 2) && ($available_torpedoes > 0))
	{
		if (round($xenobeinfo['credits'] / 3) > $available_torpedoes)
		{
			$purchase = ($available_torpedoes * 3);
			$xenobeinfo['credits'] = $xenobeinfo['credits'] - $purchase;
			$xenobeinfo['torps'] = $xenobeinfo['torps'] + $available_torpedoes;
			$gent = 'purchased ' . $available_torpedoes . ' torpedoes for ' . $purchase . ' credits,';
		}
		if (round($xenobeinfo['credits'] / 3) <= $available_torpedoes)
		{
		$purchase = (round($xenobeinfo['credits'] / 3));
			$xenobeinfo['torps'] = $xenobeinfo['torps'] + $purchase;
			$gent = 'purchased ' . $purchase . ' torpedoes for ' . $xenobeinfo['credits'] . ' credits,';
			$xenobeinfo['credits'] = 0;
		}
	}
	
	// Update xenobe database record
	$smcFunc['db_query']('', '
		UPDATE {raw:db_ships}
		SET ship_energy = {int:ship_energy},
			armor_pts = {int:armor_pts},
			ship_fighters = {int:ship_fighters},
			torps = {int:torps},
			credits = {float:credits}
		WHERE ship_id = {int:ship_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'ship_energy' => $xenobeinfo['ship_energy'],
			'armor_pts' => $xenobeinfo['armor_pts'],
			'ship_fighters' => $xenobeinfo['ship_fighters'],
			'torps' => $xenobeinfo['torps'],
			'credits' => $xenobeinfo['credits'],
			'ship_id' => $xenobeinfo['ship_id'],
		)
	);
	
	if ($gene <> '' || $gena <> '' || $genf <> '' || $gent <> '')
		playerlog($xenobeinfo['ship_id'], LOG_RAW, "Xenobe $gene $gena $genf $gent and has been updated."); 
}

function xenobetrade($xenobeinfo)
{
	global $smcFunc, $dbtables;
	global $inventory_factor, $debug;
	global $ore_price, $ore_delta, $ore_limit;
	global $goods_price, $goods_delta, $goods_limit;
	global $organics_price, $organics_delta, $organics_limit;
	
	// Obtain sector information
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_universe}
		WHERE sector_id = {int:sector}',
		array(
			'db_universe' => $dbtables['universe'],
			'sector' => $xenobeinfo['sector'],
		)
	);	
	$sectorinfo = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);

	// Obtain zone information
	$result = $smcFunc['db_query']('', '
		SELECT zone_id, allow_attack, allow_trade
		FROM {raw:db_zones}
		WHERE zone_id = {int:zone_id}',
		array(
			'db_zones' => $dbtables['zones'],
			'zone_id' => $sectorinfo['zone_id'],
		)
	);
	$zoneres = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);

	if ($debug)
		playerlog($xenobeinfo['ship_id'], LOG_RAW, "PORT $sectorinfo[port_type] ALLOW_TRADE $zonerow[allow_trade] PORE $sectorinfo[port_ore] PORG $sectorinfo[port_organics] PGOO $sectorinfo[port_goods] ORE $xenobeinfo[ship_ore] ORG $xenobeinfo[ship_organics] GOO $xenobeinfo[ship_goods] CREDITS $xenobeinfo[credits] "); 

	// Make sure we can trade here
	if ($zoneres['allow_trade'] == "N")
		return;

	// Check for a port we can use
	if ($sectorinfo['port_type'] == "none")
		return;
  
	// Xenobe do not trade at energy ports since they regen energy
	if ($sectorinfo['port_type'] == "energy")
		return;

	// Check for neg credit/cargo
	if ($xenobeinfo['ship_ore'] <= 0)
		$xenobeinfo['ship_ore'] = $shipore = 0; 
	if ($xenobeinfo['ship_organics'] <= 0)
		$xenobeinfo['ship_organics'] = $shiporganics = 0; 
	if ($xenobeinfo['ship_goods'] <= 0)
		$xenobeinfo['ship_goods'] = $shipgoods = 0; 
	if ($xenobeinfo['credits'] <= 0)
		$xenobeinfo['credits'] = $shipcredits = 0; 
	
	// Check for empty ports
	if ($sectorinfo['port_ore'] <= 0)
		return;
	if ($sectorinfo['port_organics'] <= 0)
		return;
	if ($sectorinfo['port_goods'] <= 0)
		return;

	// Check xenobe credit / cargo
	if ($xenobeinfo['ship_ore'] > 0)
		$shipore = $xenobeinfo['ship_ore'];
	if ($xenobeinfo['ship_organics'] > 0)
		$shiporganics = $xenobeinfo['ship_organics'];
	if ($xenobeinfo['ship_goods'] > 0)
		$shipgoods = $xenobeinfo['ship_goods'];
	if ($xenobeinfo['credits'] > 0)
		$shipcredits = $xenobeinfo['credits'];
  
	// Make sure we have cargo or credits
	if ($xenobeinfo['credits'] <= 0 && $xenobeinfo['ship_ore'] <= 0 && $xenobeinfo['ship_goods'] <= 0 && $xenobeinfo['ship_organics'] <= 0)
		return;

	// Make sure cargos compatible
	if ($sectorinfo['port_type'] == "ore" && $shipore > 0)
		return;
	if ($sectorinfo['port_type'] == "organics" && $shiporganics > 0)
		return;
	if ($sectorinfo['port_type'] == "goods" && $shipgoods > 0)
		return;

	// Begin trading
	
	// Ore Port
	if ($sectorinfo['port_type'] == "ore")
	{
		// Set prices
		$ore_price = $ore_price - $ore_delta * $sectorinfo['port_ore'] / $ore_limit * $inventory_factor;
		$organics_price = $organics_price + $organics_delta * $sectorinfo['port_organics'] / $organics_limit * $inventory_factor;
		$goods_price = $goods_price + $goods_delta * $sectorinfo['port_goods'] / $goods_limit * $inventory_factor;

		// Set cargo buy and sell
		$amount_organics = $xenobeinfo['ship_organics'];
		$amount_goods = $xenobeinfo['ship_goods'];
	
		// Since we sell all other holds we set amount to be our total hold limit
		$amount_ore = NUM_HOLDS($xenobeinfo['hull']);
		// We adjust this to make sure it does not exceed what the port has to sell
		$amount_ore = min($amount_ore, $sectorinfo['port_ore']);
		// We adjust this to make sure it does not exceed what we can afford to buy
		$amount_ore = min($amount_ore, floor(($xenobeinfo['credits'] + $amount_organics * $organics_price + $amount_goods * $goods_price) / $ore_price));

		// Buy and sell cargo
		$total_cost = round(($amount_ore * $ore_price) - ($amount_organics * $organics_price + $amount_goods * $goods_price));
		$newcredits = max(0,$xenobeinfo['credits'] - $total_cost);
		$newore = $xenobeinfo['ship_ore'] + $amount_ore;
		$neworganics = max(0,$xenobeinfo['ship_organics'] - $amount_organics);
		$newgoods = max(0,$xenobeinfo['ship_goods'] - $amount_goods);
	
		// Update xenobe cargo
		$smcFunc['db_query']('', '
			UPDATE {raw:db_ships}
			SET rating = rating + 1,
				credits = {float:newcredits},
				ship_ore = {int:newore},
				ship_organics = {int:neworganics},
				ship_goods = {int:newgoods}
			WHERE ship_id = {int:ship_id}',
			array(
				'db_ships' => $dbtables['ships'],
				'ship_id' => $xenobeinfo['ship_id'],
				'newcredits' => $newcredits,
				'newore' => $newore,
				'neworganics' => $neworganics,
				'newgoods' => $newgoods,
			)
		);
   
		// Update port supplies
		$smcFunc['db_query']('', '
			UPDATE {raw:db_universe}
			SET port_ore = port_ore + {int:amount_ore},
				port_organics = port_organics + {int:amount_organics},
				port_goods = port_goods + {int:amount_goods}
			WHERE sector_id = {int:sector_id}',
			array(
				'db_universe' => $dbtables['universe'],
				'sector_id' => $sectorinfo['sector_id'],
				'amount_ore' => $amount_ore,
				'amount_organics' => $amount_organics,
				'amount_goods' => $amount_goods,
			)
		);
    
		playerlog($xenobeinfo['ship_id'], LOG_RAW, "Xenobe Trade Results: Sold $amount_organics Organics Sold $amount_goods Goods Bought $amount_ore Ore Cost $total_cost"); 
	}
	
	// Organics Port
	if ($sectorinfo['port_type'] == "organics")
	{
		// Set prices
		$organics_price = $organics_price - $organics_delta * $sectorinfo['port_organics'] / $organics_limit * $inventory_factor;
		$ore_price = $ore_price + $ore_delta * $sectorinfo['port_ore'] / $ore_limit * $inventory_factor;
		$goods_price = $goods_price + $goods_delta * $sectorinfo['port_goods'] / $goods_limit * $inventory_factor;

		// Set cargo buy and sell
		$amount_ore = $xenobeinfo['ship_ore'];
		$amount_goods = $xenobeinfo['ship_goods'];
	
		// Since we sell all other holds we set amount to be our total hold limit
		$amount_organics = NUM_HOLDS($xenobeinfo['hull']);
		// We adjust this to make sure it does not exceed what the port has to sell
		$amount_organics = min($amount_organics, $sectorinfo['port_organics']);
		// We adjust this to make sure it does not exceed what we can afford to buy
		$amount_organics = min($amount_organics, floor(($xenobeinfo['credits'] + $amount_ore * $ore_price + $amount_goods * $goods_price) / $organics_price));
    
		// Buy and sell cargo
		$total_cost = round(($amount_organics * $organics_price) - ($amount_ore * $ore_price + $amount_goods * $goods_price));
		$newcredits = max(0,$xenobeinfo['credits'] - $total_cost);
		$newore = max(0,$xenobeinfo['ship_ore'] - $amount_ore);
		$neworganics = $xenobeinfo['ship_organics'] + $amount_organics;
		$newgoods = max(0,$xenobeinfo['ship_goods'] - $amount_goods);
	
		// Update xenobe cargo
		$smcFunc['db_query']('', '
			UPDATE {raw:db_ships}
			SET rating = rating + 1,
				credits = {float:newcredits},
				ship_ore = {int:newore},
				ship_organics = {int:neworganics},
				ship_goods = {int:newgoods}
			WHERE ship_id = {int:ship_id}',
			array(
				'db_ships' => $dbtables['ships'],
				'ship_id' => $xenobeinfo['ship_id'],
				'newcredits' => $newcredits,
				'newore' => $newore,
				'neworganics' => $neworganics,
				'newgoods' => $newgoods,
			)
		);
   
		// Update port supplies
		$smcFunc['db_query']('', '
			UPDATE {raw:db_universe}
			SET port_ore = port_ore + {int:amount_ore},
				port_organics = port_organics + {int:amount_organics},
				port_goods = port_goods + {int:amount_goods}
			WHERE sector_id = {int:sector_id}',
			array(
				'db_universe' => $dbtables['universe'],
				'sector_id' => $sectorinfo['sector_id'],
				'amount_ore' => $amount_ore,
				'amount_organics' => $amount_organics,
				'amount_goods' => $amount_goods,
			)
		);
    
		playerlog($xenobeinfo['ship_id'], LOG_RAW, "Xenobe Trade Results: Sold $amount_goods Goods Sold $amount_ore Ore Bought $amount_organics Organics Cost $total_cost"); 
	}
	
	// Goods Port
	if ($sectorinfo['port_type'] == "goods")
	{
		// Set prices
		$goods_price = $goods_price - $goods_delta * $sectorinfo['port_goods'] / $goods_limit * $inventory_factor;
		$ore_price = $ore_price + $ore_delta * $sectorinfo['port_ore'] / $ore_limit * $inventory_factor;
		$organics_price = $organics_price + $organics_delta * $sectorinfo['port_organics'] / $organics_limit * $inventory_factor;

		// Set cargo buy and sell
		$amount_ore = $xenobeinfo['ship_ore'];
		$amount_organics = $xenobeinfo['ship_organics'];
	
		// Since we sell all other holds we set amount to be our total hold limit
		$amount_goods = NUM_HOLDS($xenobeinfo['hull']);
		// We adjust this to make sure it does not exceed what the port has to sell
		$amount_goods = min($amount_goods, $sectorinfo['port_goods']);
		// We adjust this to make sure it does not exceed what we can afford to buy
		$amount_goods = min($amount_goods, floor(($xenobeinfo['credits'] + $amount_ore * $ore_price + $amount_organics * $organics_price) / $goods_price));
   
		// Buy and sell cargo
		$total_cost = round(($amount_goods * $goods_price) - ($amount_organics * $organics_price + $amount_ore * $ore_price));
		$newcredits = max(0,$xenobeinfo['credits'] - $total_cost);
		$newore = max(0,$xenobeinfo['ship_ore'] - $amount_ore);
		$neworganics = max(0,$xenobeinfo['ship_organics'] - $amount_organics);
		$newgoods = $xenobeinfo['ship_goods'] + $amount_goods;
	
		// Update xenobe cargo
		$smcFunc['db_query']('', '
			UPDATE {raw:db_ships}
			SET rating = rating + 1,
				credits = {float:newcredits},
				ship_ore = {int:newore},
				ship_organics = {int:neworganics},
				ship_goods = {int:newgoods}
			WHERE ship_id = {int:ship_id}',
			array(
				'db_ships' => $dbtables['ships'],
				'ship_id' => $xenobeinfo['ship_id'],
				'newcredits' => $newcredits,
				'newore' => $newore,
				'neworganics' => $neworganics,
				'newgoods' => $newgoods,
			)
		);
   
		// Update port supplies
		$smcFunc['db_query']('', '
			UPDATE {raw:db_universe}
			SET port_ore = port_ore + {int:amount_ore},
				port_organics = port_organics + {int:amount_organics},
				port_goods = port_goods + {int:amount_goods}
			WHERE sector_id = {int:sector_id}',
			array(
				'db_universe' => $dbtables['universe'],
				'sector_id' => $sectorinfo['sector_id'],
				'amount_ore' => $amount_ore,
				'amount_organics' => $amount_organics,
				'amount_goods' => $amount_goods,
			)
		);
    
		playerlog($xenobeinfo['ship_id'], LOG_RAW, "Xenobe Trade Results: Sold $amount_ore Ore Sold $amount_organics Organics Bought $amount_goods Goods Cost $total_cost"); 
	}
}

function xenobehunter($xenobeinfo)
{
	global $smcFunc, $dbtables;
	global $targetlink;
	
	$xenobeisdead = false;
	
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_ships}
		WHERE ship_destroyed = "N"
		AND xenobe = "N"
		ORDER BY score DESC
		LIMIT 0,10',
		array(
			'db_ships' => $dbtables['ships'],
			'sector' => $targetlink,
		)
	);

	// Lets choose a target from the top player list
	$i = 1;
	$targetnum = rand(1,$smcFunc['db_num_rows']($result));
	while ($row = $smcFunc['db_fetch_assoc']($result))
	{
		if ($i == $targetnum)
		{
			$targetinfo = $row;
			continue;
		}
		$i++;
	}
	
	$smcFunc['db_free_result']($result);
	
	// Make sure we have a target
	if (!isset($targetinfo))
	{
		playerlog($xenobeinfo['ship_id'], LOG_RAW, "Hunt Failed: No Target ");
		return;
	}

	// Realspace move to target sector
	$result = $smcFunc['db_query']('', '
		SELECT sector_id, zone_id
		FROM {raw:db_universe}
		WHERE sector_id = {int:sector_id}',
		array(
			'db_universe' => $dbtables['universe'],
			'sector_id' => $targetinfo['sector'],
		)
	);
	$sectrow = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
	
	$result = $smcFunc['db_query']('', '
		SELECT zone_id,allow_attack
		FROM {raw:db_zones}
		WHERE zone_id = {int:zone_id}',
		array(
			'db_zones' => $dbtables['zones'],
			'zone_id' => $sectrow['zone_id'],
		)
	);
	$zonerow = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);
	
	// Check if target sector allows attacking
	if ($zonerow['allow_attack'] == "Y")
	{
		$smcFunc['db_query']('', '
			UPDATE {raw:db_ships}
			SET last_login = NOW(),
				turns_used = turns_used + 1,
				sector = {int:sector}
			WHERE ship_id = {int:ship_id}',
			array(
				'db_ships' => $dbtables['ships'],
				'sector' => $targetinfo['sector'],
				'ship_id' => $xenobeinfo['ship_id'],
			)
		);

		playerlog($xenobeinfo['ship_id'], LOG_RAW, "Xenobe moved via realspace to sector $targetinfo[sector] where he is hunting player $targetinfo[character_name]."); 
		
		// Run sector defence checks
		$xenobeisdead = xenobetosecdef($xenobeinfo,$targetinfo['sector']);
		if ($xenobeisdead)
			return true;

		// Attack target
		playerlog($xenobeinfo['ship_id'], LOG_RAW, "Xenobe launching an attack on $targetinfo[character_name]."); 

		// Check if target is on a planet
		if ($targetinfo['planet_id'] > 0)
			$xenobeisdead = xenobetoplanet($xenobeinfo,$targetinfo['planet_id']);
		else
			$xenobeisdead = xenobetoship($xenobeinfo,$targetinfo['ship_id']);
	} 
	else
		playerlog($xenobeinfo['ship_id'], LOG_RAW, "Xenobe hunt failed, target $targetinfo[character_name] was in a no attack zone (sector $targetinfo[sector]).");
	
	return $xenobeisdead;
}

function xenobetoplanet($xenobeinfo,$planet_id)
{
	global $smcFunc, $dbtables;
	global $torp_dmg_rate, $level_factor, $rating_combat_factor;
	global $upgrade_cost, $upgrade_factor, $basedefense;

	/*
	$lock = $smcFunc['db_query']('', '
		LOCK TABLES
		{raw:db_ships} WRITE,
		{raw:db_universe} WRITE,
		{raw:db_logs} WRITE,
		{raw:db_planets} WRITE,
		{raw:db_news} WRITE',
		array(
			'db_ships' => $dbtables['ships'],
			'db_universe' => $dbtables['universe'],
			'db_logs' => $dbtables['logs'],
			'db_planets' => $dbtables['planets'],
			'db_news' => $dbtables['news'],
		)
	);
	*/
	
	// Get planet information
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_planets}
		WHERE planet_id = {int:planet_id}',
		array(
			'db_planets' => $dbtables['planets'],
			'planet_id' => $planet_id,
		)
	);
	$planetinfo = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);

	// Get planet owner information
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_ships}
		WHERE ship_id = {int:owner}',
		array(
			'db_ships' => $dbtables['ships'],
			'owner' => $planetinfo['owner'],
		)
	);
	$ownerinfo = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);

	// Setup planetary variables
	$base_factor = ($planetinfo['base'] == 'Y') ? $basedefense : 0;

	// Planet beams
	$targetbeams = NUM_BEAMS($ownerinfo['beams'] + $base_factor);
	if ($targetbeams > $planetinfo['energy'])
		$targetbeams = $planetinfo['energy'];
	$planetinfo['energy'] -= $targetbeams;
    
	// Planet shields
	$targetshields = NUM_SHIELDS($ownerinfo['shields'] + $base_factor);
	if ($targetshields > $planetinfo['energy'])
		$targetshields = $planetinfo[energy];
	$planetinfo['energy'] -= $targetshields;
    
	// Planet torps
	$torp_launchers = round(mypw($level_factor, ($ownerinfo['torp_launchers'])+ $base_factor)) * 10;
	$torps = $planetinfo['torps'];
	$targettorps = $torp_launchers;
	if ($torp_launchers > $torps)
		$targettorps = $torps;
	$planetinfo['torps'] -= $targettorps;
	$targettorpdmg = $torp_dmg_rate * $targettorps;

	// Planet fighters
	$targetfighters = $planetinfo['fighters'];

	// Setup attacker variables
	// Attacker beams
	$attackerbeams = NUM_BEAMS($xenobeinfo['beams']);
	if ($attackerbeams > $xenobeinfo['ship_energy'])
		$attackerbeams = $xenobeinfo['ship_energy'];
	$xenobeinfo['ship_energy'] -= $attackerbeams;

	// Attacker shields
	$attackershields = NUM_SHIELDS($xenobeinfo['shields']);
	if ($attackershields > $xenobeinfo['ship_energy'])
		$attackershields = $xenobeinfo['ship_energy'];
	$xenobeinfo['ship_energy'] -= $attackershields;

	// Attacker torps
	$attackertorps = round(mypw($level_factor, $xenobeinfo['torp_launchers'])) * 2;
	if ($attackertorps > $xenobeinfo['torps'])
		$attackertorps = $xenobeinfo['torps']; 
	$xenobeinfo['torps'] -= $attackertorps;
	$attackertorpdamage = $torp_dmg_rate * $attackertorps;

	// Attacker fighters
	$attackerfighters = $xenobeinfo['ship_fighters'];

	// Attacker armor
	$attackerarmor = $xenobeinfo['armor_pts'];

	// Begin combat
	// Attacker has beams - target has fighters - beams vs fighters
	if ($attackerbeams > 0 && $targetfighters > 0)
	{
		// Attacker beams greater than target fighters
		if ($attackerbeams > $targetfighters)
		{
			// Target loses all fighters
			// Attacker loses beams equal to target fighters
			$lost = $targetfighters;
			$targetfighters = 0;
			$attackerbeams = $attackerbeams - $lost;
		}
		// Attacker beams less than target fighters
		else
		{
			// Target loses fighters equal to attacker beams
			// Attacker loses all beams
			$targetfighters = $targetfighters - $attackerbeams;
			$attackerbeams = 0;
		}   
	}
	
	// Target has beams - attacker has fighters - beams vs fighters
	if ($attackerfighters > 0 && $targetbeams > 0)
	{
		// Attacker beams greater than half target fighters
		if ($targetbeams > round($attackerfighters / 2))
		{
			// Attacker loses half of all fighters
			// Target loses beams equal to half of target fighters
			$lost = $attackerfighters - (round($attackerfighters / 2));
			$attackerfighters = $attackerfighters - $lost;
			$targetbeams = $targetbeams - $lost;
		}
		// Attacker beams less than half target fighters
		else
		{
			// Target loses fighters equal to attacker beams
			// Attacker loses all beams
			$attackerfighters = $attackerfighters - $targetbeams;
			$targetbeams = 0;
		}   
	}
  
	// Attacker has beams left - continue combat - beams vs shields
	if ($attackerbeams > 0)
	{
		// Attacker beams greater than target shields
		if ($attackerbeams > $targetshields)
		{
			// Attacker loses beams equal to target shields
			// Target loses all shields
			$attackerbeams = $attackerbeams - $targetshields;            
			$targetshields = 0;                                        
		}
		// Attacker beams less than target shields
		else
		{
			// Target loses shields equal to attacker beams
			// Attacker loses all beams
			$targetshields = $targetshields - $attackerbeams;
			$attackerbeams = 0;
		}
	}
  
	// Target has beams left - continue combat - beams vs shields
	if ($targetbeams > 0)
	{
		// Target beams greater than attacker shields
		if ($targetbeams > $attackershields)
		{
			// Target loses beams equal to attacker shields
			// Attacker loses all shields
			$targetbeams = $targetbeams - $attackershields;            
			$attackershields = 0;                                        
		}
		// Target beams less than attacker shields
		else
		{
			// Attacker loses shields equal to target beams
			// Target loses all beams
			$attackershields = $attackershields - $targetbeams;
			$targetbeams = 0;
		}
	}

	// Target has beams left - continue combat - beams vs armor
	if ($targetbeams > 0)
	{
		// Target beams greater than attacker armor
		if ($targetbeams > $attackerarmor)
		{
			// Target loses beams equal to attacker armor
			// Attacker loses all armor
			$targetbeams = $targetbeams - $attackerarmor;            
			$attackerarmor = 0;                                        
		}
		// Target beams less than attacker armor
		else
		{
			// Attacker loses armor equal to target beams
			// Target loses all beams
			$attackerarmor = $attackerarmor - $targetbeams;
			$targetbeams = 0;
		}
	}

	// Attacker has torps - target has fighters - torps vs fighters
	if ($targetfighters > 0 && $attackertorpdamage > 0)
	{
		// Attacker torps greater than target fighters
		if ($attackertorpdamage > $targetfighters)
		{
			// Target loses half all fighters
			// Attacker loses half torps equal to half of target fighters
			$lost = $targetfighters;
			$targetfighters = 0;
			$attackertorpdamage = $attackertorpdamage - $lost;
		}
		// Attacker torps less than target fighters
		else
		{
			// Target loses fighters equal to attacker torps
			// Attacker loses all torps
			$targetfighters = $targetfighters - $attackertorpdamage;
			$attackertorpdamage = 0;
		}   
	}

	// Target has torps - Attacker has fighters - torps vs fighters
	if ($attackerfighters > 0 && $targettorpdmg > 0)
	{
		// Target torps greater than half of attacker fighters
		if ($targettorpdmg > round($attackerfighters / 2))
		{
			// Attacker loses half all fighters
			// Target loses torps equal to half of target fighters
			$lost = $attackerfighters - (round($attackerfighters / 2));
			$attackerfighters = $attackerfighters - $lost;
			$targettorpdmg = $targettorpdmg - $lost;
		}
		// Target torps less than half of attacker fighters
		else
		{
			// Attacker loses fighters equal to target torps
			// Attacker loses all torps
			$attackerfighters = $attackerfighters - $targettorpdmg;
			$targettorpdmg = 0;
		}   
	}

	// Target has torps left - continue combat - torps vs armor
	if ($targettorpdmg > 0)
	{
		// Target torps greater than attacker armor
		if ($targettorpdmg > $attackerarmor)
		{
			// Target loses torps equal to attacker armor
			// Attacker loses all armor - destroyed
			$targettorpdmg = $targettorpdmg - $attackerarmor;            
			$attackerarmor = 0;                                        
		}
		// Target torps less than attacker armor
		else
		{
			// Attacker loses armor equal to target torps
			// Target loses all torps
			$attackerarmor = $attackerarmor - $targettorpdmg;
			$targettorpdmg = 0;
		}
	}

	// Attacker has fighters - target has fighters - fighters vs fighters
	if ($attackerfighters > 0 && $targetfighters > 0)
	{
		// Attacker fighters greater than target fighters
		if ($attackerfighters > $targetfighters)
			// Target will lose all fighters
			$temptargfighters = 0;
		// Attacker fighters less than target fighters
		else
			// Target will lose fighters equal to attacker fighters
			$temptargfighters = $targetfighters - $attackerfighters;
		
		// Target fighters greater than attacker fighters
		if ($targetfighters > $attackerfighters)
			// Attacker will lose all fighters
			$tempplayfighters=0;
		// Target fighters less than attacker fighters
		else
			// Attacker will lose fighters equal to target fighters
			$tempplayfighters=$attackerfighters-$targetfighters;
			
		$attackerfighters = $tempplayfighters;
		$targetfighters = $temptargfighters;
	}
	
	// Target has fighters - continue combat - fighters vs armor
	if ($targetfighters > 0)
	{
		// Target fighters greater than attacker armor
		if ($targetfighters > $attackerarmor)
			// Attacker loses all armor - attacker destroyed
			$attackerarmor = 0;
		// Target fighters less than attacker armor
		else
			// Attacker looses armor equal to target fighters
			$attackerarmor = $attackerarmor - $targetfighters;
	}

	// Check for and fix negative value vars
	$attackerfighters = ($attackerfighters < 0) ? 0 : $attackerfighters;
	$attackershields = ($attackershields < 0) ? 0 : $attackershields;
	$attackerbeams = ($attackerbeams < 0) ? 0 : $attackerbeams;
	$attackerarmor = ($attackerarmor < 0) ? 0 : $attackerarmor;
	
	$targetfighters = ($targetfighters < 0) ? 0 : $targetfighters;
	$targettorpdmg = ($targettorpdmg < 0) ? 0 : $targettorpdmg;
	$targetshields = ($targetshields < 0) ? 0 : $targetshields;
	$targetbeams = ($targetbeams < 0) ? 0 : $targetbeams;

	// Check if attacker ship destroyed
	if ($attackerarmor <= 0)
	{
		$xenobeisdead = true;
		
	    playerlog($xenobeinfo['ship_id'], LOG_RAW, "Ship destroyed by planetary defenses on planet $planetinfo[name]");
		db_kill_player($xenobeinfo['ship_id']);

		$free_ore = round($xenobeinfo['ship_ore'] / 2);
		$free_organics = round($xenobeinfo['ship_organics'] / 2);
		$free_goods = round($xenobeinfo['ship_goods'] / 2);
	
		$ship_value = $upgrade_cost * (round(mypw($upgrade_factor, $xenobeinfo['hull'])) + round(mypw($upgrade_factor, $xenobeinfo['engines'])) + round(mypw($upgrade_factor, $xenobeinfo['power'])) + round(mypw($upgrade_factor, $xenobeinfo['computer'])) + round(mypw($upgrade_factor, $xenobeinfo['sensors'])) + round(mypw($upgrade_factor, $xenobeinfo['beams'])) + round(mypw($upgrade_factor, $xenobeinfo['torp_launchers'])) + round(mypw($upgrade_factor, $xenobeinfo['shields'])) + round(mypw($upgrade_factor, $xenobeinfo['armor'])) + round(mypw($upgrade_factor, $xenobeinfo['cloak'])));
		$ship_salvage_rate = rand(10,20);
		$ship_salvage = $ship_value * $ship_salvage_rate / 100;
		
		$fighters_lost = $planetinfo['fighters'] - $targetfighters;

		// Log attack to planet owner
		playerlog($planetinfo['owner'], LOG_PLANET_NOT_DEFEATED, "$planetinfo[name]|$xenobeinfo[sector]|Xenobe $xenobeinfo[character_name]|$free_ore|$free_organics|$free_goods|$ship_salvage_rate|$ship_salvage");

		// Update planet information
		$smcFunc['db_query']('', '
			UPDATE {raw:db_planets}
			SET energy = {int:energy},
				fighters = fighters - {int:fighters_lost},
				torps = torps - {int:targettorps},
				ore = ore + {int:free_ore},
				goods = goods + {int:free_goods},
				organics = organics + {int:free_organics}, 
				credits = credits + {float:ship_salvage} 
			WHERE planet_id = {int:planet_id}',
			array(
				'db_planets' => $dbtables['planets'],
				'planet_id' => $planetinfo['planet_id'],
				'energy' => $planetinfo['energy'],
				'fighters_lost' => $fighters_lost,
				'targettorps' => $targettorps,
				'free_ore' => $free_ore,
				'free_goods' => $free_goods,
				'free_organics' => $free_organics,
				'ship_salvage' => $ship_salvage,
			)
		);
	}
	else
	{
		$xenobeisdead = false;
		
		$armor_lost = $xenobeinfo['armor_pts'] - $attackerarmor;
		$fighters_lost = $xenobeinfo['ship_fighters'] - $attackerfighters;
		$target_fighters_lost = $planetinfo['ship_fighters'] - $targetfighters;
		playerlog($xenobeinfo['ship_id'], LOG_RAW, "Made it past defenses on planet $planetinfo[name]");

		// Update xenobe information
		$smcFunc['db_query']('', '
			UPDATE {raw:db_ships}
			SET ship_energy = {int:energy},
				ship_fighters = ship_fighters - {int:fighters_lost},
				armor_pts = armor_pts - {int:armor_lost}, 
				torps = torps - {int:attackertorps}
			WHERE ship_id = {int:ship_id}',
			array(
				'db_ships' => $dbtables['ships'],
				'ship_id' => $xenobeinfo['ship_id'],
				'energy' => $xenobeinfo['ship_energy'],
				'fighters_lost' => $fighters_lost,
				'armor_lost' => $armor_lost,
				'attackertorps' => $attackertorps,
			)
		);

		$xenobeinfo['ship_fighters'] = $attackerfighters;
		$xenobeinfo['torps'] = $attackertorps;
		$xenobeinfo['armor_pts'] = $attackerarmor;


		// Update planet information
		$smcFunc['db_query']('', '
			UPDATE {raw:db_planets}
			SET energy = {int:energy},
				fighters = fighters - {int:fighters_lost},
				torps = torps - {int:targettorps} 
			WHERE planet_id = {int:planet_id}',
			array(
				'db_planets' => $dbtables['planets'],
				'planet_id' => $planetinfo['planet_id'],
				'energy' => $planetinfo['energy'],
				'fighters_lost' => $target_fighters_lost,
				'targettorps' => $targettorps,
			)
		);

		$planetinfo['fighters'] = $targetfighters;
		$planetinfo['torps'] = $targettorps;

		/*
			Xenobe begins to attack all ships on the planet.
			Xenobe will continue to attack until all on planet ships are destroyed,
			or until the xenoboe destroys himself.
		*/
		do
		{
			$result = $smcFunc['db_query']('', '
				SELECT ship_id, ship_name
				FROM {raw:db_ships}
				WHERE planet_id = {int:planet_id}
				AMD on_planet = "Y"',
				array(
					'db_ships' => $dbtables['ships'],
					'planet_id' => $planetinfo['planet_id'],
				)
			);
			while ($onplanet = $smcFunc['db_fetch_assoc']($result) && $xenobeisdead == false)
			{
				$xenobeisdead = xenobetoship($xenobeinfo,$onplanet['ship_id']);
			}
			$smcFunc['db_free_result']($result);
			
			$result = $smcFunc['db_query']('', '
				SELECT ship_id, ship_name
				FROM {raw:db_ships}
				WHERE planet_id = {int:planet_id}
				AMD on_planet = "Y"',
				array(
					'db_ships' => $dbtables['ships'],
					'planet_id' => $planetinfo['planet_id'],
				)
			);
		}
		while ($smcFunc['db_num_rows']($result) <> 0 && $xenobeisdead == false);
		
		// Check if xenobe is still alive
		if ($xenobeisdead == false)
		{
			// Log xenobe destroyed all ships on the planet
			playerlog($xenobeinfo['ship_id'], LOG_RAW, "Defeated all ships on planet $planetinfo[name]");
			
			// Log attack to planet owner
			playerlog($planetinfo['owner'], LOG_PLANET_DEFEATED, "$planetinfo[name]|$xenobeinfo[sector]|$xenobeinfo[character_name]");

			// Update planet
			$smcFunc['db_query']('', '
				UPDATE {raw:db_planets}
				SET owner = 0,
					fighters = 0,
					torps = 0,
					base = "N",
					defeated = "Y",
					owner = 0,
					corp = 0
				WHERE planet_id = {raw:planet_id}',
				array(
					'db_planets' => $dbtables['planets'],
					'planet_id' => $planetinfo['planet_id']
				)
			);
			calc_ownership($planetinfo['sector_id']);
		}
		else
		{
			// Xenobe died while trying to capture planet
			playerlog($xenobeinfo['ship_id'], LOG_RAW, "We were KILLED by ships defending planet $planetinfo[name]");
			
			// Log attack to planet owner
			playerlog($planetinfo['owner'], LOG_PLANET_NOT_DEFEATED, "$planetinfo[name]|$xenobeinfo[sector]|Xenobe $xenobeinfo[character_name]|0|0|0|0|0");
		}
	}
  
	// $unlock = $smcFunc['db_query']('', 'UNLOCK TABLES');
	
	return $xenobeisdead;
}
?>
